// ActionScript file
package FileSearch
{
import flash.events.DataEvent;
import flash.events.ErrorEvent;
import flash.events.EventDispatcher;
import flash.events.FileListEvent;
import flash.filesystem.File;
import flash.media.Sound;

import mx.collections.ArrayCollection;
import mx.collections.IList;
import mx.controls.Alert;

public final class FileSearch extends EventDispatcher
{

	private var fileTypes:Array;	
	private var queue:Array;
	private var res:mx.collections.IList;
	
	public function FileSearch(fileTypes:Array, res:mx.collections.IList)
	{
		this.fileTypes = fileTypes;
		this.res = res;
		this.queue = new Array();
	}
	
	public function search(root:File):void
	{
		if (root.isDirectory){
			root.addEventListener(FileListEvent.DIRECTORY_LISTING, _DirectoryListingHandler);
			root.addEventListener(ErrorEvent.ERROR, _ioErrorHandler);
			root.getDirectoryListingAsync();
		}
		else{
			if (isValidType(root.extension)){
				dispatchEvent(new FileSearchEvent(root, res));
			}
			if (queue.length != 0)
			{
				var next:File = queue.shift();
				search(next);
			}
		}
	}
	
	protected function _DirectoryListingHandler(event:FileListEvent):void
	{
		((event.target) as File).removeEventListener(FileListEvent.DIRECTORY_LISTING, _DirectoryListingHandler);
		((event.target) as File).removeEventListener(ErrorEvent.ERROR, _ioErrorHandler);
		for each(var  f:File in event.files){
			// empiler
			queue.push(f);
		}
		if (queue.length != 0)
		{
			var next:File = queue.shift();
			search(next);
		}
	}

	protected function _ioErrorHandler(event:ErrorEvent):void
	{
		Alert.show("Can't open file " + event.target.toString());
	}
	
	public function isValidType(type:String):Boolean
	{
		for each (var s:String in fileTypes) 
		{
			if (type == s)
				return true;
		}
		
		return false;
	}
	

}
}